#include "buttonrelay.h"
#include <QPainter>

ButtonRelay::ButtonRelay(Button& button)
{
    mPixmapBackground.load(tr("://images/btn_background.png"));
    {
        mButton.mCId = button.mCId;
        mButton.mBId = button.mBId;
        mButton.mRId = button.mRId;
        mButton.mName = button.mName;
        mButton.mNotUsed = button.mNotUsed;

        mButton.mPos = button.mPos;
        mButton.mX = button.mX;
        mButton.mY = button.mY;
        mButton.mCX = button.mCX;
        mButton.mCY = button.mCY;

        mButton.mRType = button.mRType;
        mButton.mStatus = button.mStatus;

        mButton.mWidget = button.mWidget;
    }
    setStatus(mButton.mStatus);
}

QSize ButtonRelay::sizeHint() const
{
    QSize size = QPushButton::sizeHint();

    if (mPixmapBackground.isNull()) {
        size.setWidth(DefWidth);
        size.setHeight(DefHeight);
    } else {
        size = mPixmapBackground.size();
    }

    return size;
}

void ButtonRelay::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);
    QPainter painter;

    painter.begin(this);
    if (false == mPixmapBackground.isNull()) {
        painter.drawPixmap(0, 0, mPixmapBackground);
        painter.drawText(QRectF(0, 0, mPixmapBackground.size().width(), 28), Qt::AlignCenter, mButton.mName);
        if (false == mPixmapStatus.isNull()) {
            painter.drawPixmap(4, 28, mPixmapStatus);
        }
    } else {
        painter.drawText(QRectF(0, 0, DefWidth, DefHeight), Qt::AlignCenter, mButton.mName);
    }
    painter.end();
}

const Button *ButtonRelay::button()
{
    return &mButton;
}

void ButtonRelay::setStatus(int status)
{
    QString fileName;

    switch (status) {
    case RELAY_STATUS_OFF:
        fileName = tr("://images/status_off.png");
        break;
    case RELAY_STATUS_ON:
        fileName = mButton.mRType ? tr("://images/status_ready.png") : tr("://images/status_on.png");
        break;
    case RELAY_STATUS_AIR:
        fileName = tr("://images/status_air.png");
        break;
    case RELAY_STATUS_COOLING:
        fileName = tr("://images/status_cooling.png");
        break;
    case RELAY_STATUS_HEATING:
        fileName = tr("://images/status_heating.png");
        break;
    case RELAY_STATUS_PENDING:
        fileName = tr("://images/status_pending.png");
        //fileName = tr("://images/status_shutdown.png");
        break;
    case RELAY_STATUS_UNKNOWN:
        fileName = tr("://images/status_unknown.png");
        break;
    case RELAY_STATUS_NOTUSED:
    default:
        fileName = tr("://images/status_off.png");
        setEnabled(false);
        break;
    }

    if (fileName.length()) {
        mPixmapStatus.load(fileName);

        if (false == isEnabled()) {
            setEnabled(true);
        }
    }

    mButton.mStatus = status;

    update();
}
